package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 缓存查询服务累类型
    @Override
    public Result queryType() {
        // 1.在缓存中查询
        List<String> cacheList = stringRedisTemplate.opsForList().range(CACHE_SHOPTYPE_KEY, 0, -1);
        // 2.存在，返回
        List<ShopType> typeList;
        if(cacheList!=null && !cacheList.isEmpty()){
            typeList = JSONUtil.toList(cacheList.get(0),ShopType.class);
            return Result.ok(typeList);
        }
        // 3.不存在，在数据库中查询
        typeList = query().orderByAsc("sort").list();
        // 4.不存在，报异常
        if(typeList == null || typeList.isEmpty()){
            return Result.fail("数据异常！");
        }
        // 5.存在，存到redis中
        String typeListJson = JSONUtil.toJsonStr(typeList);
        stringRedisTemplate.opsForList().leftPushAll(CACHE_SHOPTYPE_KEY,typeListJson);
        // 6.返回结果
        log.info("服务类型：{}",typeList);
        return Result.ok(typeList);
    }

}
